from sync_http import get_shops_status
from async_http import notify_all
import asyncio
import time
import random
from datetime import datetime


# from data import shops


def init_shops():
    intime_shops = get_shops_status()
    shops = {}
    for each in intime_shops:
        name = each['shop_name']
        shop_id = each['id']
        is_open = int(each['is_open'])
        shops[shop_id] = {"name": name, "status": is_open}
    return shops


def update_loop(start, end):
    shops = init_shops()
    print(shops)
    print("开始检测")
    while True:
        now = datetime.now().hour
        if now < start or now > end:
            time.sleep(5)
            print(datetime.now(), "未到检测时间")
            continue
        new_status = get_shops_status()

        open_shops = []

        for new_shop in new_status:
            nid = new_shop['id']
            status = int(new_shop['is_open'])
            if nid not in shops.keys():
                continue
            else:
                # print("正在检测商店: {0}的状态".format(shops[nid]['name']))
                if shops[nid]['status'] != status and status != 0:
                    open_shops.append(shops[nid])
                    shops[nid]['status'] = status
                    # msg = "{0}开门啦!".format(shops[nid]['name'])
                    # print(msg)
                elif status == 0:
                    # print("关门了:{0}".format(shops[nid]['name']))
                    pass
        if open_shops:
            msg = "开门啦" + "、".join([each['name'] for each in open_shops])
            routine = notify_all(msg)
            asyncio.run(routine)
        else:
            pass
        update_sleep = 5 + random.randint(0, 100) / 10
        print("update_sleep", update_sleep)
        print(shops)
        time.sleep(update_sleep)


if __name__ == '__main__':
    update_loop(8, 17)
    # init_shops()
